﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO;
using System.Threading;

namespace iTunesSync
{
    public partial class DuplicateDetector : Form
    {
        private delegate void addSongDelegate(ListViewItem item);

        public DuplicateDetector()
        {
            InitializeComponent();
        }

        private void DuplicateDetector_Load(object sender, EventArgs e)
        {
            loadiTunesDuplicates();
        }

        private void loadiTunesDuplicates()
        {
            new Thread(new ParameterizedThreadStart(loadiTunesDuplicatesWorker)).Start();
        }

        private void loadiTunesDuplicatesWorker(object obj)
        {
            string[] files = Directory.GetFiles(Environment.GetFolderPath(Environment.SpecialFolder.MyMusic) + "\\iTunes\\iTunes Media\\Music");
            foreach (string file in files)
            {
                FileInfo fileData = new FileInfo(file);
                foreach (string check in files)
                {
                    FileInfo checkData = new FileInfo(check);
                    if (fileData.Length == checkData.Length)
                    {
                        addSong(new ListViewItem(new[] { parseName(file), fileData.Length.ToString() }));
                        addSong(new ListViewItem(new[] { parseName(check), checkData.Length.ToString() }));
                    }
                }
            }
        }

        private void addSong(ListViewItem item)
        {
            if (InvokeRequired)
            {
                BeginInvoke(new addSongDelegate(addSong), new object[] { item });
                return;
            }
            //
            listView1.Items.Add(item);
        }

        private string parseName(string file)
        {
            return file.Remove(0, file.LastIndexOf("\\") + 1);
        }
    }
}
